package cn.xlbweb.cli.util;

import cn.xlbweb.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * @author: bobi
 * @date: 2021/2/18 下午5:40
 * @description:
 */
@Component
public class JdbcUtils {

    private static JdbcTemplate jdbcTemplate = SpringUtils.getBean(JdbcTemplate.class);

    public static Map<String, Object> getOne(String sql, Object[] params) {
        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, params);
        if (!CollectionUtils.isEmpty(results)) {
            return results.get(0);
        }
        return null;
    }

    public static List<Map<String, Object>> findAll(String sql, Object[] params) {
        return jdbcTemplate.queryForList(sql, params);
    }

    public static List<Map<String, Object>> findAll(String sql, Object[] params, Integer page, Integer size) {
        String pageSql = StringUtils.join(sql, " limit ", page, ", ", size);
        return jdbcTemplate.queryForList(pageSql, params);
    }
}
